package com.fjnldx.mes.service.scheduling.alarm.rule.inspector.trigger;

import com.alibaba.fastjson.JSONObject;
import com.fjnldx.mes.domain.pojo.alarm.enums.TriggerConditionEnum;
import com.fjnldx.mes.domain.pojo.alarm.enums.TriggerTypeEnum;
import com.fjnldx.mes.service.scheduling.alarm.mapper.AlarmSchedulingMapper;
import com.fjnldx.mes.service.scheduling.alarm.model.MonitorModel;
import com.fjnldx.mes.service.scheduling.alarm.rule.inspector.contrast.AlarmContrast;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 累次触发器
 */
@Service
public class CumulativeTrigger implements AlarmTrigger {

    @Resource
    private AlarmSchedulingMapper alarmSchedulingMapper;

    private final List<AlarmContrast> alarmContrastList;

    public CumulativeTrigger(List<AlarmContrast> alarmContrasts) {
        this.alarmContrastList = alarmContrasts;
    }

    @Override
    public TriggerTypeEnum TriggerType() {
        return TriggerTypeEnum.CUMULATIVE;
    }

    @Override
    public MonitorModel isTriggered(String cs, String tableName, String devSn, String triggerValue, String conditionSql) {
        JSONObject triggerConfig = JSONObject.parseObject(triggerValue);
        //对比操作符
        TriggerConditionEnum condition = triggerConfig.getObject("operator", TriggerConditionEnum.class);
        //标准值
        String standardValue = triggerConfig.getString("standard");
        //累计次数
        Integer number = triggerConfig.getInteger("number");
        //累计属性值
        List<String> csValues = alarmSchedulingMapper.getCsCumulativeValue(cs, tableName, devSn, number, conditionSql);

        List<AlarmContrast> alarmContrasts = alarmContrastList.stream().filter(contrast -> contrast.getCondition() == condition).collect(Collectors.toList());

        //拼接响应值
        MonitorModel monitor = new MonitorModel();
        monitor.setStandard(standardValue);
        monitor.setCollect(csValues.get(0));
        monitor.setOperator(condition);
        monitor.setWhetherTrigger(alarmContrasts.stream().anyMatch(contrast -> {
            //累计数据全部符合条件
            return csValues.stream().allMatch(value -> contrast.Contrast(value, standardValue));
        }));
        return monitor;
    }
}
